package com.feonix.common.datasource;

import com.feonix.common.util.NumberUtil;
import com.feonix.common.util.StringUtil;

public class DataSourceSwitch {
	private static final ThreadLocal<String> DB_TYPE = new ThreadLocal<String>();

	private static final ThreadLocal<String> POOL_ALIAS = new ThreadLocal<String>();

	public static void change(String alias) {
		if (StringUtil.isNotEmpty(alias)) {
			DB_TYPE.set(alias);
			POOL_ALIAS.set(DataSourceManager.getDataSourcesConfig().get(alias).getDbType());
		}
	}

	public static void changeDefault() {
		DB_TYPE.remove();
		POOL_ALIAS.remove();
	}

	static String getAlias() {
		String dbType = DB_TYPE.get();
		if (StringUtil.isEmpty(dbType)) {
			dbType = DataSourceManager.getDefaultDataSourceConfig().getAlias();
		}
		return dbType;
	}

	public static String getCurrentAlias() {
		return getAlias();
	}

	public static int getDbType() {
		String str = POOL_ALIAS.get();
		if (StringUtil.isEmpty(str)) {
			str = DataSourceManager.getDefaultDataSourceConfig().getDbType();
		}
		return NumberUtil.getInt(str);
	}
}
